import React, { useEffect, useState } from 'react';
import {
  Form,
  Card,
  Space,
  Input,
  Typography,
  Image,
  DatePicker,
  Checkbox,
  Radio,
  Button,
  Message,
  Modal,
} from '@arco-design/web-react';
import { SSSUpload } from '../../../components/upload';
import { BankSelect } from '../../../components/bank-select';
import { GlobalState } from '@/store';
import { useSelector } from 'react-redux';
import { queryEnterInfo, enter } from '@/services/merchant';
import { FormValues } from './constant';
import {
  convertFormValueToApiParam,
  convertApiRespToFormValue,
  validateLegalPersonIdCardExpireTime,
} from './utils';
import styles from './style/index.module.less';
import { ActionFooter } from '../../../components/action-footer';

const RadioGroup = Radio.Group;

const InputWrapperCol = { span: 8 };

export default function Page() {
  const [form] = Form.useForm<FormValues>();
  const [loading, setLoading] = useState(false);

  const userInfo = useSelector((state: GlobalState) => state.userInfo);

  const [bankVisible, setBankVisible] = useState(false);

  useEffect(() => {
    queryEnterInfo({ merchantId: userInfo.merchantId }).then((res) => {
      form.setFieldsValue(convertApiRespToFormValue(res?.data));
    });
  }, []);

  function handleSubmit(draft = false) {
    const apiParams = convertFormValueToApiParam(form.getFieldsValue());
    if (draft) {
      submit(apiParams, draft);
    } else {
      form
        .validate()
        .then(() => {
          submit(apiParams, draft);
        })
        .catch(() => {
          Message.error('校验失败，请按照提示填写相关项');
        });
    }
  }

  function submit(apiParams, draft = false) {
    setLoading(true);
    enter({
      merchantId: userInfo?.merchantId,
      merchantStatus: draft ? 0 : 10,
      ...apiParams,
    })
      .then(() => {
        Message.success('提交成功');
      })
      .catch((reason) => {
        Message.error(reason);
      })
      .finally(() => {
        setLoading(false);
      });
  }

  return (
    <>
      <div className={styles.container}>
        <Form form={form} initialValues={{ accountType: 'company' }}>
          <Card>
            <Typography.Title heading={6}>商户信息</Typography.Title>
            <Form.Item
              label={'商户名称'}
              field="merchantName"
              rules={[{ required: true, message: '请输入商户名称' }]}
              extra={
                <>
                  <div>
                    保护注册商标原则：名称不得侵犯注册商标专用权，否则审核将不被通过或面临法律诉讼；
                  </div>
                  <div>
                    认证名称唯一原则：名称不得与已认证名称重复，否则审核将不被通过。
                  </div>
                </>
              }
            >
              <Input placeholder={'请输入商户名称'} className="arco-col-8" />
            </Form.Item>
            <Form.Item
              label={'商户管理员微信二维码'}
              field="managerWxCode"
              rules={[
                { required: true, message: '请上传商户管理员微信二维码' },
              ]}
            >
              <SSSUpload
                name="上传二维码"
                desc="认证审核过程中，审核人员有可能会添加此微信号做后续认证操作。"
              />
            </Form.Item>
            <Form.Item
              label={'《商标注册书》和《商标授权书》'}
              field="tradeMarkAuthorization"
            >
              <SSSUpload
                name="上传文件"
                desc="特殊情况可上传作为佐证，如企业工商变更证明、商标证书、品牌授权证明、加盖公章证明等。"
              />
            </Form.Item>
          </Card>
          <Card>
            <Typography.Title heading={6}>企业认证信息</Typography.Title>
            <Form.Item
              label={'营业执照'}
              field="businessLicense"
              rules={[{ required: true, message: '请上传营业执照' }]}
            >
              <SSSUpload
                name="上传营业执照"
                desc={
                  <Space>
                    <Image
                      width={82}
                      height={82}
                      src={require('./assets/yyzz.jpg')}
                    />
                    <Typography.Text
                      type="secondary"
                      style={{ fontSize: 12, color: 'var(--color-text-3)' }}
                    >
                      附件说明：文件大小不超过10M；支持格式：.png .jpg .jpeg
                      .bmp
                    </Typography.Text>
                  </Space>
                }
              />
            </Form.Item>
            <Form.Item
              wrapperCol={InputWrapperCol}
              label={'企业全称'}
              field="companyName"
              rules={[{ required: true, message: '请输入企业名称' }]}
            >
              <Input placeholder="请输入企业名称" />
            </Form.Item>
            <Form.Item
              wrapperCol={InputWrapperCol}
              label={'统一社会信用代码'}
              field="socialCreditCode"
              rules={[{ required: true, message: '请输入统一社会信用代码' }]}
            >
              <Input placeholder="请输入统一社会信用代码" />
            </Form.Item>
            <Form.Item
              required
              label={'法定代表人身份证'}
              extra={
                '（附件说明：必须无遮挡且清晰不模糊；文件大小不超过10M；支持格式：.png .jpg .jpeg .bmp）'
              }
            >
              <Space>
                <Form.Item
                  noStyle={{ showErrorTip: true }}
                  field="legalPersonIdCardFront"
                  rules={[{ required: true, message: '请上传身份证正面' }]}
                >
                  <SSSUpload name="上传身份证正面" />
                </Form.Item>
                <Form.Item
                  noStyle={{ showErrorTip: true }}
                  field="legalPersonIdCardBack"
                  rules={[{ required: true, message: '请上传身份证反面' }]}
                >
                  <SSSUpload name="上传身份证反面" />
                </Form.Item>
              </Space>
            </Form.Item>
            <Form.Item
              wrapperCol={InputWrapperCol}
              label={'法定代表人姓名'}
              field="legalPersonName"
              extra="个体工商户填经营者信息"
              rules={[{ required: true, message: '请输入法定代表人姓名' }]}
            >
              <Input placeholder="请输入法定代表人姓名" />
            </Form.Item>
            <Form.Item
              wrapperCol={InputWrapperCol}
              label={'法定代表身份证号'}
              field="legalPersonIdCard"
              rules={[
                {
                  required: true,
                  message: '请输入法定代表身份证号',
                },
                {
                  validateTrigger: 'onBlur',
                  message: '身份证号格式不正确',
                  match:
                    /^(^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|X|x)$)|(^[1-9]\d{7}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}$)$/,
                },
              ]}
            >
              <Input placeholder="请输入法定代表身份证号" />
            </Form.Item>
            <Form.Item
              shouldUpdate
              required
              label={'身份证有效截止日期'}
              extra={'（证件有效期需大于60天）'}
            >
              {(values) => {
                return (
                  <Space>
                    <Form.Item
                      disabled={Boolean(values['legalPersonIdCardNotExpire'])}
                      noStyle={{ showErrorTip: true }}
                      field="legalPersonIdCardExpireTimeStr"
                      rules={[
                        {
                          validator: (_value, callback) =>
                            validateLegalPersonIdCardExpireTime(form, callback),
                        },
                      ]}
                    >
                      <DatePicker placeholder={'身份证有效截止日期'} />
                    </Form.Item>
                    <Form.Item
                      triggerPropName={'checked'}
                      noStyle
                      field="legalPersonIdCardNotExpire"
                      rules={[
                        {
                          validator: (_value, callback) =>
                            validateLegalPersonIdCardExpireTime(form, callback),
                        },
                      ]}
                    >
                      <Checkbox>长期</Checkbox>
                    </Form.Item>
                  </Space>
                );
              }}
            </Form.Item>
            <Form.Item
              wrapperCol={InputWrapperCol}
              label={'法定代表人联系邮箱'}
              field="legalPersonEmail"
              rules={[
                {
                  required: true,
                  message: '请输入法定代表人联系邮箱',
                },
                {
                  validateTrigger: 'onBlur',
                  message: '邮箱格式不正确',
                  match: /^[A-Za-z0-9+_.-]+@(.+)$/,
                },
              ]}
              extra={'（邮箱用于接收重要信息通知，请保证邮箱真实可用）'}
            >
              <Input placeholder="请输入法定代表人联系邮箱" />
            </Form.Item>
          </Card>
          <Card>
            <Typography.Title heading={6}>收款账户信息</Typography.Title>
            <Form.Item
              required
              label={'收款账户类型'}
              field="accountType"
              extra={<div style={{ color: 'red' }}>一经选择不能修改</div>}
            >
              <RadioGroup>
                <Radio value="company">对公账户</Radio>
                <Radio value="person">个人账户</Radio>
              </RadioGroup>
            </Form.Item>
            <Form.Item noStyle shouldUpdate>
              {(values) => {
                const accountType = values['accountType'];
                let label;
                let value;
                switch (accountType) {
                  case 'company':
                    label = '开户名称';
                    value = values['companyName'];
                    break;
                  case 'person':
                    label = '持卡人姓名';
                    value = values['legalPersonName'];
                    break;
                }
                return (
                  <Form.Item label={label} wrapperCol={InputWrapperCol}>
                    <Typography.Text>{value}</Typography.Text>
                  </Form.Item>
                );
              }}
            </Form.Item>
            <Form.Item
              wrapperCol={InputWrapperCol}
              label={'开户银行名称'}
              field="bankName"
              rules={[{ required: true, message: '请选择开户银行' }]}
              onClick={() => setBankVisible(true)}
            >
              <Input placeholder="请选择开户银行" readOnly />
            </Form.Item>
            <Form.Item
              required
              wrapperCol={InputWrapperCol}
              label={'开户支行名称'}
              field={'bankBranchName'}
            >
              <Input readOnly />
            </Form.Item>
            <Form.Item
              wrapperCol={InputWrapperCol}
              label={'开户支行地区'}
              field={'bankCity'}
              hidden
            >
              <Input readOnly />
            </Form.Item>
            <Form.Item
              wrapperCol={InputWrapperCol}
              rules={[{ required: true, message: '请输入银行账号' }]}
              label={'银行账号'}
              field="bankAccount"
            >
              <Input placeholder="请输入银行账号" />
            </Form.Item>

            <Form.Item noStyle shouldUpdate>
              {(values) => {
                const accountType = values['accountType'];
                let label;
                switch (accountType) {
                  case 'company':
                    label = '开户许可证照片';
                    break;
                  case 'person':
                    label = '银行卡照片';
                    break;
                }
                return (
                  <Form.Item
                    label={label}
                    field="bankLicense"
                    rules={[
                      { required: true, message: '请上传开户许可证照片' },
                    ]}
                  >
                    <SSSUpload
                      name="上传许可证照片"
                      desc="文件大小不超过10M；支持格式：.png .jpg .jpeg .bmp"
                    />
                  </Form.Item>
                );
              }}
            </Form.Item>
          </Card>
        </Form>
        <ActionFooter>
          <Button>取消</Button>
          <Button loading={loading} onClick={() => handleSubmit(true)}>
            保存草稿
          </Button>
          <Button
            type="primary"
            loading={loading}
            onClick={() => handleSubmit()}
          >
            提交申请
          </Button>
        </ActionFooter>
      </div>
      <Modal
        style={{ width: '800px' }}
        title="开户行选择"
        footer={null}
        visible={bankVisible}
        onOk={() => setBankVisible(false)}
        onCancel={() => setBankVisible(false)}
        autoFocus={false}
        focusLock={true}
        unmountOnExit
      >
        <BankSelect
          onSelect={(record) => {
            setBankVisible(false);
            form.setFieldsValue({
              bankName: record.bankName,
              bankBranchName: record.subBankName,
              bankCity: {
                province: record.province,
                city: record.city,
                area: record.area,
              },
            });
          }}
        />
      </Modal>
    </>
  );
}
